package a51qindian.com.comprehensive.activity;

import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.text.InputType;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;

import com.li.widget.MultipleLayout;
import com.li.widget.PersonalDetailItem;
import com.li.widget.TopNavigationBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import a51qindian.com.comprehensive.R;
import a51qindian.com.comprehensive.base.QDBaseActivity;
import a51qindian.com.comprehensive.net.ObservableHelper;
import a51qindian.com.comprehensive.net.RetrofitCreator;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;


/**
 * Author: Li
 * Date: 2017/10/16 0016
 * Description: 新增优惠券列表
 */

public class AddCouponActivity extends QDBaseActivity {

    @BindView(R.id.top_navigation)
    TopNavigationBar mTopNavigation;
    @BindView(R.id.layout_content)
    MultipleLayout mLayoutContent;
    @BindView(R.id.layout_name)
    PersonalDetailItem mLayoutName;
    @BindView(R.id.layout_money)
    PersonalDetailItem mLayoutMoney;
    @BindView(R.id.layout_condition)
    PersonalDetailItem mLayoutCondition;
    @BindView(R.id.layout_num)
    PersonalDetailItem mLayoutNum;
    @BindView(R.id.layout_start)
    PersonalDetailItem mLayoutStart;
    @BindView(R.id.layout_end)
    PersonalDetailItem mLayoutEnd;
    @BindView(R.id.layout_useful)
    PersonalDetailItem mLayoutUseful;

    private String mEnable;
    private static final int REQUEST_GET_NAME = 0x1;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_add_coupon;
    }

    @Override
    protected void initSth() {
        super.initSth();
        mTopNavigation.setNavigationBarListener(this);
        mLayoutStart.getTxtRight().setHint("选择开始时间");
        mLayoutEnd.getTxtRight().setHint("选择结束时间");
    }

    @OnClick({R.id.layout_name, R.id.layout_money, R.id.layout_condition, R.id.layout_useful,
            R.id.layout_num, R.id.layout_start, R.id.layout_end, R.id.btn_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_name:
                showEditDialog("输入优惠券名称",InputType.TYPE_CLASS_TEXT,mLayoutName);
                break;
            case R.id.layout_money:
                showEditDialog("输入优惠券金额", InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL,
                        mLayoutMoney);
                break;
            case R.id.layout_condition:
                showEditDialog("使用条件（0：不限）", InputType.TYPE_CLASS_TEXT, mLayoutCondition);
                break;
            case R.id.layout_num:
                showEditDialog("输入发放数量（0：不限）", InputType.TYPE_CLASS_NUMBER, mLayoutNum);
                break;
            case R.id.layout_start:
                showDateDialog(mLayoutStart);
                break;
            case R.id.layout_end:
                showDateDialog(mLayoutEnd);
                break;
            case R.id.layout_useful:
                showEnableDialog(mLayoutUseful);
                break;
            case R.id.btn_confirm:
                addCoupon(mUid, mLayoutName.getTxtRightContent(), mLayoutMoney.getTxtRightContent(),
                        mLayoutCondition.getTxtRightContent(), mLayoutNum.getTxtRightContent(),
                        mLayoutStart.getTxtRightContent(),
                        mLayoutEnd.getTxtRightContent(), mEnable);
                break;
        }
    }

    /**
     * 添加优惠券
     *
     * @param uid            用户编号
     * @param name           优惠券名称
     * @param money          优惠券价格
     * @param condition      使用条件
     * @param createNum      发放数量
     * @param use_start_time 开始时间
     * @param use_end_time   结束时间
     * @param status         是否使用 0：不启用  1：启用
     */
    private void addCoupon(String uid, String name, String money, String condition,
                           String createNum, String use_start_time, String use_end_time, String status) {
        mLayoutContent.onLoadingWithContent();
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        map.put("name", name);
        map.put("money", money);
        map.put("condition", condition);
        map.put("createnum", createNum);
        map.put("use_start_time", use_start_time);
        map.put("use_end_time", use_end_time);
        map.put("status", status);
        ObservableHelper.createObservable(RetrofitCreator.createService().addCoupon(map))
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        mLayoutContent.onSuccess();
                        try {
                            JSONObject object=new JSONObject(s);
                            showToast(object.getString("info"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mLayoutContent.onSuccess();
                        showToast(e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    /**
     * 显示选择日期对话框
     *
     * @param item 需要更新的View
     */
    private void showDateDialog(final PersonalDetailItem item) {
        DatePickerDialog datePickerDialog = new DatePickerDialog(AddCouponActivity.this,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        String y = String.valueOf(year);
                        String m = month < 9 ? ("0" + (month + 1)) : String.valueOf(month + 1);
                        String d = dayOfMonth < 10 ? ("0" + dayOfMonth) : String.valueOf(dayOfMonth);
                        item.setTxtRight(y + "-" + m + "-" + d);
                    }
                },
                Calendar.getInstance().get(Calendar.YEAR),
                Calendar.getInstance().get(Calendar.MONTH),
                Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
        datePickerDialog.show();
    }

    private void showEditDialog(String hint, int inputType, final PersonalDetailItem item) {
        View updateView = getLayoutInflater().inflate(R.layout.layout_update_dialog, null);
        final EditText editText = updateView.findViewById(R.id.et_update);
        editText.setInputType(inputType);
        editText.setHint(hint);
        AlertDialog.Builder builder = new AlertDialog.Builder(AddCouponActivity.this)
                .setTitle("提示")
                .setView(updateView)
                .setNegativeButton("取消", null)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        item.setTxtRight(editText.getText().toString());
                        mEnable = String.valueOf(which);
                    }
                });
        builder.create().show();
    }

    private void showEnableDialog(final PersonalDetailItem item) {
        AlertDialog.Builder builder = new AlertDialog.Builder(AddCouponActivity.this)
                .setTitle("是否启用")
                .setItems(new String[]{"不启用", "启用"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String s = which == 0 ? "不启用" : "启用";
                        item.setTxtRight(s);
                    }
                });
        builder.create().show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_GET_NAME && resultCode == RESULT_OK) {
            String name = data.getStringExtra("name");
            mLayoutName.setTxtRight(name);
        }
    }
}
